﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CounterServerModel;
using System.Data;
using CounterServerModel.Authentication;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.IO;

namespace SmartCounters
{
	public partial class SendBillsForm : System.Web.UI.Page
	{

		public static string k_BillsToSendSessionKey = "BillsToSend";
		List<Bill> m_BillsToSend;

		protected void Page_Load(object sender, EventArgs e)
		{
			((MainTemplate)Master).m_PagePermissionFilter = MainTemplate.k_AdminPageFilter;
		}

		protected void Page_Prerender(object sender, EventArgs e)
		{
			m_BillsToSend = Session[k_BillsToSendSessionKey] as List<Bill>;
			rpBillsToSendList.DataSource = m_BillsToSend;
			rpBillsToSendList.ItemDataBound += rpBillsToSendList_ItemDataBound;
			rpBillsToSendList.DataBind();
			
		}

		void rpBillsToSendList_ItemDataBound(Object sender, RepeaterItemEventArgs e)
		{
			// treat only items ignore all others
			if ((e.Item.ItemType != ListItemType.Item) && (e.Item.ItemType != ListItemType.AlternatingItem))
				return;

			InformationReader infoProvider = new InformationReader();
			
			Bill bill = e.Item.DataItem as Bill;
			AccountInfo account = infoProvider.GetAccountInformation(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials, bill.AccountID);
			string accountAdressString = account.Country + " " + account.City + " " + account.Street + " " + account.House + "/" + account.Apartment;

			List<UserInfo> AssociatedUsers = new List<UserInfo>();
			foreach (int userID in account.UsersAssociatedWith)
			{
				UserInfo assoiciatedUser = infoProvider.GetUserInformation(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials, userID);
				AssociatedUsers.Add(assoiciatedUser);
			}

			Label lblBillTitle = e.Item.FindControl("BillTile") as Label;
			Repeater rpAssociatedUsers = e.Item.FindControl("rpAssociatedUser") as Repeater;
			Label lblYear = e.Item.FindControl("lblYear") as Label;
			Label lblMonth = e.Item.FindControl("lbMonth") as Label;
			Label lblTotalUsage = e.Item.FindControl("lblTotalUsage") as Label;
			Label lblSumToPay = e.Item.FindControl("lblTotalSum") as Label;
			
			lblBillTitle.Text += "Account# " + account.AccountID + " " + accountAdressString;
			
			rpAssociatedUsers.DataSource = AssociatedUsers;
			rpAssociatedUsers.ItemDataBound += rpAssociatedUsers_ItemDataBound;
			rpAssociatedUsers.DataBind();

			lblYear.Text += bill.Year;
			lblMonth.Text += bill.Month;
			lblTotalUsage.Text += bill.TotalUsage;
			lblSumToPay.Text += bill.SumPaid;
			
		}

		void rpAssociatedUsers_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			// treat only items ignore all others
			if ((e.Item.ItemType != ListItemType.Item) && (e.Item.ItemType != ListItemType.AlternatingItem))
				return;

			UserInfo user = e.Item.DataItem as UserInfo;

			Label lblUsername = e.Item.FindControl("lblUsername") as Label;
			Label lblEmail = e.Item.FindControl("lblEmail") as Label;

			lblUsername.Text = user.Username;
			lblEmail.Text = user.Email;
		}

		protected void CreateAndEmailBills(object sender, EventArgs e)
		{
			createBills();
			emailBills();
			Session[k_BillsToSendSessionKey] = null;
			Response.Redirect("/Administration/BillsManagement.aspx");
		}

		private void createBills()
		{
			m_BillsToSend = Session[k_BillsToSendSessionKey] as List<Bill>;
			BillingService billingService = new BillingService();

			foreach (Bill bill in m_BillsToSend)
			{
				try
				{
					billingService.CreateBill(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials, bill.AccountID, bill.Year, bill.Month);
				}
				catch
				{ 
				}
			}
		}


		private void emailBills()
		{
			MailAddress fromAddress = new MailAddress("SmartCounters@gmail.com");
			string fromPassword = "watercounters";
			
			SmtpClient client = new SmtpClient();
			client.Host = "smtp.gmail.com";
			client.Port = 587;
			client.EnableSsl = true;
			client.DeliveryMethod = SmtpDeliveryMethod.Network;
			client.UseDefaultCredentials = false;
			client.Credentials = new NetworkCredential(fromAddress.Address, fromPassword);

			foreach (RepeaterItem billItem in rpBillsToSendList.Items)
			{
				if ((billItem.ItemType == ListItemType.Item) || (billItem.ItemType == ListItemType.AlternatingItem))
				{
					Label lblBillTitle = billItem.FindControl("BillTile") as Label;
					Repeater rpAssociatedUsers = billItem.FindControl("rpAssociatedUser") as Repeater;
					foreach (RepeaterItem userItem in rpAssociatedUsers.Items)
					{
						if ((userItem.ItemType == ListItemType.Item) || (userItem.ItemType == ListItemType.AlternatingItem))
						{
							Label lblEmail = userItem.FindControl("lblEmail") as Label;

							MailAddress toAddress = new MailAddress(lblEmail.Text);

							StringBuilder billHtmlFormat = new StringBuilder();
							StringWriter tw = new StringWriter(billHtmlFormat);
							HtmlTextWriter hw = new HtmlTextWriter(tw);
							billItem.RenderControl(hw);

							MailMessage message = new MailMessage(fromAddress, toAddress);
							message.IsBodyHtml = true;
							string subject = lblBillTitle.Text;
							string body = billHtmlFormat.ToString();
							message.Subject = subject;
							message.Body = body;
							client.Send(message);
						}
					}
				}
			}
		}


	}
}
